/****************
 *@description: 调拨入库单详情   procurement/allocateIn/add
 *@author: Xhd
 *@date: 2023-07-24 11:01:38
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from 'react';
import { Form, Input, Select, Space, message, Modal } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import GoBack from '@/components/TheGoBack'
import { apiStockSupplierManageList, apiStockLibraryManageList } from '@/request/storageManager/store.js'
import { apiStockInLibraryAdd, apiStockInLibraryView, apiStockInLibraryDetailsAdd, apiStockInLibraryDetailsRevokeDetail, apiStockInLibraryDetailsRevokeConfirmInLibrary } from '@/request/procurement/putIn.js'
import { apiGetGoodsList, apiGetGoodsDetail } from '@/request/marketingTool'
import { exportSheetTable } from '@/utils/exportTable.js'
import store from "@/store/store"

const { Option } = Select
const { TextArea } = Input
const { Search } = Input

export default class OutPutAdd extends Component {
  constructor() {
    super()
    this.FormRef = React.createRef()
    this.addFormRef = React.createRef()
    this.state = {
      searchDataSource: [],
      columns: [
        {
          title: "序号",
          dataIndex: "index",
          key: "index",
          render: (text, record, index) => {
            return ((this.state.pageData.pageNo - 1) * (this.state.pageData.pageSize) + (index + 1));
          }
        },
        {
          title: "商品名称",
          dataIndex: "goodsName",
          key: "goodsName",
        },
        {
          title: '物料名称',
          dataIndex: 'materialName',
          key: 'materialName'
        },
        {
          title: "规格",
          dataIndex: "goodsSkuName",
          key: "goodsSkuName",
        },
        {
          title: "物料ID",
          dataIndex: "goodsSkuNo",
          key: "goodsSkuNo",
        },
        {
          title: "入库前库存",
          dataIndex: "beforeCount",
          key: "beforeCount",
        },
        {
          title: "入库数量",
          dataIndex: "count",
          key: "count",
        },
        {
          title: '入库价格',
          dataIndex: "unitPrice",
          key: "unitPrice",
          render: (text) => {
            return (text / 100).toFixed(2)
          }
        },
        {
          title: "操作时间",
          dataIndex: "createTime",
          key: "createTime",
        }, 
        {
          title: "操作人",
          dataIndex: "memberName",
          key: "memberName",
        }, 
        // {
        //   title: "操作",
        //   render: (text, render, index) => {
        //     return <div>
        //       <TheButton haspermi={['storage:putIn:delInfo']} onClick={() => this.del(render, index)}>删除</TheButton>
        //     </div>
        //   }
        // },
      ],
      dataSource: [],
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      isModalVisible: false,
      loading: false,
      isSave: false,
      id: null,
      storeList: [],
      supplierList: [],
      code: '',
      libraryId: '',
      inLibraryId: '',
      dataId: '',
      productSku: [],
      currentSku: [],
      goodsList: [],
      materialId: '',
      options: [
        { label: '采购入库单转入库单', value: 1 },
        { label: '商城退货退款入库单', value: 2 },
        { label: '门店退货退款入库单', value: 3 },
        { label: '门店收银台退货', value: 4 },
        { label: '手动创建入库单', value: 5 },
        { label: '调拨入库单', value: 6 },
      ],
      details: [],
      status: null,
      dataType: null,
      isAdd: false

    }
  }
  componentDidMount() {
    this.setState({
      id: this.props.match.params.id
    }, async () => {
      let res1 = await this.getStores()
      if (!res1.data || res1.data.length === 0) {
        store.dispatch({
          type: 'SavePageTabValue',
          data: {
            tab: 'store'
          }
        })
        Modal.warning({
          title: '提示',
          content: '尚未创建仓库，是否立即添加仓库？',
          okText: '去添加',
          onOk: () => {
            this.props.history.push('/storageManager/store?')
          }
        });
        return
      }
      let res2 = await this.getSuppliers()
      if (!res2.data || res2.data.length === 0) {
        store.dispatch({
          type: 'SavePageTabValue',
          data: {
            tab: 'provide'
          }
        })
        Modal.warning({
          title: '提示',
          content: '尚未创建供应商，是否立即添加供应商？',
          okText: '去添加',
          onOk: () => {
            this.props.history.push('/storageManager/store')
          }
        });
        return
      }
      if (this.state.id !== 'null') {
        this.getView()
      } else {
        this.FormRef.current.setFieldsValue({
          libraryId: this.state.storeList[0].id,
          supplierId: this.state.supplierList[0].id
        })
      }
    })
  }
  del(row, index) {
    console.log(row);
    React.$confirm({
      title: "提示",
      type: 'warning',
      content: "确定是否删除？",
      onOk: async () => {
        let res = await apiStockInLibraryDetailsRevokeDetail({
          id: row.id,
          dataType: row.dataType,
          goodsSkuId: row.goodsSkuId,
          count: row.count,
          inLibraryId: this.state.inLibraryId,
          dataId: row.dataId ? row.dataId : ''
        })
        if (res.code === 0) {
          let dataSource = this.state.dataSource
          dataSource.splice(index, 1)
          this.setState({
            searchDataSource: []
          }, () => {
            this.setState({
              searchDataSource: dataSource
            })
          })
          React.$message({
            type: 'success',
            content: res.codeMessage
          })
        } else {
          React.$message({
            type: 'warning',
            content: res.codeMessage
          })
        }



      }
    });

  }
  async getView() {
    let res = await apiStockInLibraryView({ id: this.state.id })
    if (res.code === 0) {
      await this.getGoodsList(res.data.libraryId)
      if (res.data.dataType === 5) {
        this.setState({
          isAdd: true
        })
      }
      this.setState({
        isSave: true,
        details: res.data,
        dataSource: this.state.dataSource.concat(res.data.stockInLibraryDetailsVos),
        code: res.data.code,
        inLibraryId: res.data.id,
        libraryId: res.data.libraryId,
        status: res.data.status,
        dataType: res.data.dataType,
        dataId: res.data.dataId,
        searchDataSource: this.state.dataSource.concat(res.data.stockInLibraryDetailsVos),

      })
      this.FormRef.current.setFieldsValue({
        libraryId: res.data.libraryId,
        supplierId: res.data.supplierId,
        remark: res.data.remark ? res.data.remark : ' '
      })
      if (res.data.status === 1 || res.data.dataType !== 5) {
        let columns = this.state.columns
        columns.pop()
        this.setState({
          columns: []
        }, () => {
          this.setState({
            columns: columns
          })
        })
      }

    }
  }
  async getGoodsList(libraryId) {
    let res = await apiGetGoodsList({ libraryId, type: 1 })
    if (res.code === 0) {
      this.setState({
        goodsList: res.data,
      })
    }
  }
  selectFilter(input, option) {
    const materialIds = option.option.materialIds.toLowerCase().split(',')
    const result = option.children.toLowerCase().includes(input.toLowerCase()) || materialIds.includes(input.toLowerCase())
    return result
  }
  goodsChange(e, row) {
    this.apiGetGoodsDetail(e)
  }
  async apiGetGoodsDetail(goodsId) {
    let res = await apiGetGoodsDetail({ goodsId, libraryId: this.state.libraryId })
    if (res.code === 0) {
      if (this.state.materialId) {
        let result = res.data.skuInfo.filter(item => item.materialId === this.state.materialId)
        this.setState({
          productSku: res.data,
          currentSku: result.length > 0 ? result[0] : res.data.skuInfo[0]
        })
      } else {
        this.setState({
          productSku: res.data,
          currentSku: res.data.skuInfo[0]
        })
      }
      this.addFormRef.current.setFieldsValue({
        price: res.data.skuInfo[0].price
      })
    }
  }
  // 获取供应商list
  async getSuppliers() {
    let res = await apiStockSupplierManageList()
    if (res.code === 0) {
      this.setState({
        supplierList: res.data
      })
    }
    return res
  }
  // 获取仓库list
  async getStores() {
    let res = await apiStockLibraryManageList()
    if (res.code === 0) {
      this.setState({
        storeList: res.data
      })
    }
    return res
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  };
  triggerSkuTag(row) {
    this.setState({
      currentSku: row
    })
    this.addFormRef.current.setFieldsValue({
      price: row.price
    })
  }
  async onFinishAdd(values) {
    let { inLibraryId, currentSku, code } = this.state
    let res = await apiStockInLibraryDetailsAdd({
      inLibraryId: inLibraryId,
      goodsSkuId: currentSku.SKUId,//skuId
      dataType: 5,
      code: code,
      count: values.nowCount,//盘点库存
      unitPrice: (values.price) * 100, //入库价格
      beforeCount: currentSku.stock,//当前库存
    })
    if (res.code === 0) {
      message.success(res.codeMessage);
      this.reset()
      this.setState({
        dataSource: this.state.dataSource.concat(res.data),
        searchDataSource: this.state.dataSource.concat(res.data),

        isModalVisible: false
      })

    }
  }
  onFinishSearch() { }
  setSearchValue = (value) => {
    const { dataSource } = this.state
    let search = value.target.value.trim()
    if (search) {
      this.setState({
        searchDataSource: this.getSearchData(dataSource, search)
      })
    } else {
      this.setState({
        searchDataSource: this.state.dataSource
      })
    }
  }
  getSearchData(aim, searchVal) {
    let newArr = []
    for (var i = 0; i < aim.length; i++) {
      let value = aim[i].goodsName, value1 = aim[i].goodsSkuNo, value2 = aim[i].materialName
      if (value.includes(searchVal) || value1.includes(searchVal) || value2.includes(searchVal)) {
        newArr.push(aim[i]);//将值放入第二个数组
      }
    }
    return newArr
    // return aim.filter(item => item.goodsName == goodsName)
  }
  handleCancel() { }
  savePutInOrder = () => {
    Modal.confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: '保存入库单后将不可修改，确定保存入库单吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        let values = this.FormRef.current.getFieldsValue()
        let res = await apiStockInLibraryAdd({
          libraryId: values.libraryId,
          supplierId: values.supplierId,
          remark: values.remark ? values.remark : ''
        })
        if (res.code === 0) {
          this.getGoodsList(values.libraryId)
          this.setState({
            isSave: true,
            isAdd: true,
            code: res.data.code,
            inLibraryId: res.data.id,
            libraryId: values.libraryId,
            dataType: res.data.dataType
          })
        }

      }
    });
  }
  reset() {
    this.addFormRef.current.setFieldsValue({
      nowCount: null,
      goodsId: '',
      dataType: '',
      unitPrice: '',
      price: ''
    })
    this.setState({
      productSku: {},
      currentSku: {}
    })
  }
  execute() {
    React.$confirm({
      title: "提示",
      type: 'warning',
      content: "是否确定操作？",
      onOk: async () => {
        let res = await apiStockInLibraryDetailsRevokeConfirmInLibrary({
          "dataId": this.state.dataId,
          "dataType": this.state.dataType,
          "id": this.state.inLibraryId,
          "libraryId": this.state.libraryId,
          "stockInLibraryDetails": this.state.dataSource
        })
        if (res.code === 0) {
          React.$message({
            type: 'success',
            content: res.codeMessage
          })
          setTimeout(() => {
            this.props.history.go(-1)
          }, 2000);
        }
      }
    })

  }
  exportGoodsDetail() {
    const th_arr = [
      {
        title: `入库单详情(单号：${this.state.code})`,
        prop: '',
        children: [
          {
            title: '商品名称',
            prop: 'goodsName',
          },
          {
            title: '物料名称',
            prop: 'materialName'
          },
          {
            title: '规格',
            prop: 'goodsSkuName',
          },
          {
            title: "物料ID",
            prop: "goodsSkuNo",
          },
          {
            title: '入库前库存',
            prop: 'beforeCount',
            valueType: 'number'
          },
          {
            title: '入库数量',
            prop: 'count',
            valueType: 'number'
          },
          {
            title: '操作时间',
            prop: 'createTime',
          },
          {
            title: '操作人',
            prop: 'memberName',
          }

        ]
      },

    ]
    let tb_arr = this.state.dataSource
    exportSheetTable({ fileName: `入库单详情(单号：${this.state.code})`, tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false, })
  }
  onBlur = (materialId) => {
    this.setState({
      materialId
    })
  }
  render() {
    let { columns, supplierList, status, searchDataSource, libraryId, storeList, dataSource, isSave, isAdd } = this.state
    return (
      <div className="p-layout-box">
        <GoBack history={this.props.history} title="新增入库管理" />
        <Form layout={'inline'} ref={this.FormRef} onFinish={this.onFinishSearch} style={{ marginBottom: 12, marginTop: 12 }}>
          <Form.Item name={"libraryId"}>
            <Select disabled={libraryId ? true : false} style={{ width: 200 }} placeholder={"入库仓库"}>
              {
                storeList.map(item => {
                  return <Option value={item.id}>{item.name}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item name={"supplierId"}>
            <Select disabled={libraryId ? true : false} style={{ width: 200 }} placeholder={"供应商"}>
              {
                supplierList.map(item => {
                  return <Option value={item.id}>{item.supplierName}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item name={"remark"}>
            <TextArea disabled={libraryId ? true : false} autoSize={false} rows={1} style={{ width: 340 }} maxLength={60} placeholder={"备注"} />
          </Form.Item>
          <Space direction="vertical">
            <Search
              placeholder="请输入物品名称/物料ID"
              onChange={(e) => this.setSearchValue(e)}
              style={{
                width: 200,
              }}
              allowClear
            />
          </Space>
          <div style={{ marginLeft: 12 }}>
            <TheButton onClick={() => this.exportGoodsDetail()} haspermi={['storage:putIn:exportGoodsDetail']} size="middle" type="default">导出</TheButton>
          </div>
        </Form>
        {
          status !== 1 ? <div style={{ marginBottom: 12 }}>
            {
              !isSave ?
                <TheButton haspermi={['storage:putIn:savePutInOrder']} onClick={() => this.savePutInOrder()} size="middle" type="primary">保存入库单</TheButton>
                :
                isAdd ?
                  <div></div> : null
            }
          </div> : null
        }

        <TheTable
          scroll={{ x: "max-content", y: '63vh' }}
          columns={columns}
          dataSource={searchDataSource}
        />
        {

          status !== 1 ? <div style={{ textAlign: 'center', marginTop: 12 }}>
            {
              dataSource.length > 0 &&
              <TheButton type="primary" size='middle' haspermi={['storage:putIn:execute']} onClick={() => this.execute(1)}>提交</TheButton>

            }
          </div> : null
        }
      </div>
    );
  }
}
